package com.jianyun.jyzs.http.AsyTask;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;


import com.jianyun.jyzs.common.HttpResultFileVO;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.utils.FileUtil;
import com.jianyun.jyzs.utils.PathUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class AsyncTaskActDownFileUtil extends AsyncTask<Object, Integer, HttpResultFileVO> {
	
	private ProgressBar progressBar;
	
	 // 可变长的输入参数，与AsyncTask.exucute()对应  
    public AsyncTaskActDownFileUtil(){  
    }  
    public AsyncTaskActDownFileUtil(Handler handler, String remotePath, int type, ProgressBar progressBar, int what, int id, String[] fileParam) {
		this.progressBar = progressBar;
	}
    // 可变长的输入参数，与AsyncTask.exucute()对应  

	@SuppressLint("DefaultLocale")
	@Override  
    protected HttpResultFileVO doInBackground(Object... params) {
		HttpResultFileVO vo = new HttpResultFileVO();
		vo.mHandler = (Handler)params[0];
		String remotePath = String.valueOf(params[1]);
		vo.type =Integer.valueOf(String.valueOf(params[2]));
		progressBar = params[3] != null?(ProgressBar)params[3]:null;
		vo.what = Integer.valueOf(String.valueOf(params[4]));
		vo.id =Integer.valueOf(String.valueOf(params[5]));
		String[] param = null;
		String fileDir = "";
		switch (vo.what){
		case SysConstant.IMAGE:
			fileDir = PathUtil.imagePathName;
			break;
		case SysConstant.VOICE:
			fileDir = PathUtil.voicePathName;
			break;
		case SysConstant.VIDEO:
			fileDir = PathUtil.videoPathName;
			break;
		case SysConstant.FILE:
			param = (String[])params[6];
			fileDir = PathUtil.filePathName+"/"+param[1];
			break;
		default:
			break;
		}
    	if(progressBar != null){
			progressBar.setMax(100);  
			progressBar.setProgress(0);
    	}
		OutputStream output = null;
		//文件夹
		File dir = new File(fileDir);  
		if(!dir.exists()){
			dir.mkdirs();
		}

		File file = null ;
		String name = "";
		try {
			URL url = new URL(remotePath);
			// 创建一个HttpURLConnection连接  
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setRequestMethod("GET");
			urlConn.setConnectTimeout(10 * 1000);
			urlConn.connect();
			//本地文件
			int fileSize = urlConn.getContentLength();
			if(fileSize == 0){
				fileSize = 1024000;
			}
			if(vo.what == SysConstant.FILE){
				name = urlConn.getHeaderField("Content-Disposition");
				if(name != null && !name.equals("") && name.toLowerCase().indexOf("filename") != -1){
					name = new String(name.substring(name.toLowerCase().indexOf("filename")+9).getBytes("utf-8"), "utf-8");
				}else if(param[0]==null){
					vo.err="获取文件名称失败";
					return vo;
				}
				if(param[0] == null){
					file = new File(fileDir +"/"+ name);  
				}else if(param[0] != null && param[0].indexOf("_") != -1 && param[0].length() > 16){
					file = new File(fileDir +"/"+ param[0].substring(16));  
				}else{
					file = new File(fileDir +"/"+ (param[0]==null?name:param[0]));  
				}
			}else{
				file = new File(fileDir + FileUtil.getFileName(remotePath));
			}
			if(!file.exists()){
				file.createNewFile();  
				InputStream input = urlConn.getInputStream();
				//写入本地
				output = new FileOutputStream(file);  
				byte buffer [] = new byte[1024];
				int inputSize = -1;
				int updateCount = 0;
				int downloadCount = 0;
				while((inputSize = input.read(buffer)) != -1) {
					output.write(buffer, 0, inputSize);
					downloadCount += inputSize;// 时时获取下载到的大小
					/*** 每次增张2%**/
					if (updateCount == 0 || (downloadCount * 100 / fileSize - 2) >= updateCount) {
						updateCount += 2;
					}
		            this.publishProgress(updateCount);  
				}
	            this.publishProgress(100);  
				output.flush();
			}else{
				boolean delete = file.delete();
				file.createNewFile();
				InputStream input = urlConn.getInputStream();
				//写入本地
				output = new FileOutputStream(file);
				byte buffer [] = new byte[20];
				int inputSize = -1;
				int updateCount = 0;
				int downloadCount = 0;
				while((inputSize = input.read(buffer)) != -1) {
					output.write(buffer, 0, inputSize);
					downloadCount += inputSize;// 时时获取下载到的大小
					/*** 每次增张2%**/
					if (updateCount == 0 || (downloadCount * 100 / fileSize - 2) >= updateCount) {
						updateCount += 2;
					}
					this.publishProgress(updateCount);
				}
				this.publishProgress(100);
				output.flush();
			}
			if(vo.what == SysConstant.FILE){
				if(param[0] == null){
					vo.filePath = fileDir +"/"+ name;  
				}else if(param[0] != null && param[0].indexOf("_") != -1 && param[0].length() > 16){
					vo.filePath = fileDir +"/"+ param[0].substring(16);  
				}else{
					vo.filePath = fileDir +"/"+ (param[0]==null?name:param[0]);  
				}
			}else{
				vo.filePath = fileDir + FileUtil.getFileName(remotePath);
			}
			vo.isNormal = true;
		} catch (MalformedURLException e) {
			vo.err="下载文件失败";
			try {
				if (file.exists()) {
					file.delete();
				}
			} catch (Exception e2) {
			}
			e.printStackTrace();
		} catch (IOException e) {
			vo.err="下载文件失败";
			try {
				if (file.exists()) {
					file.delete();
				}
			} catch (Exception e2) {
			}
			e.printStackTrace();
		} catch (Exception e) {
			vo.err="下载文件失败";
			try {
				if (file.exists()) {
					file.delete();
				}
			} catch (Exception e2) {
			}
			e.printStackTrace();
		} finally{  
			try{  
				if(output != null){
					output.close();  
				}
			}catch(Exception e){  
				e.printStackTrace();  
			}
		}
		return vo;
	}

    @Override  
    protected void onProgressUpdate(Integer... values) {  
    	if(progressBar != null){
			progressBar.setProgress(values[0]);
    	}
    }  

    /** 
     * 在doInBackground 执行完成后，onPostExecute方法将被UI thread调用，后台的计算结果将通过该方法传递到UI thread. 
     */
    @Override  
    protected void onPostExecute(HttpResultFileVO result) {
    	try{
	    	if(result.mHandler != null && result != null){
		    	Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable(SysConstant.msg_key_parcelable, result);
				msg.setData(bundle);
				msg.what = result.what;
				result.mHandler.sendMessage(msg);
	    	}
		} catch (Exception e) {
		}
    }  

    @Override  
    protected void onCancelled() {  
    }  
	/** 
     * 该方法将在执行实际的后台操作前被UI thread调用。这个方法只是做一些准备工作，如在界面上显示一个进度条。 
     */  
    @Override  
    protected void onPreExecute() {  
    }  

}  